﻿/*********************************************************************************
 *Author:         OnClick
 *Version:        0.0.2.155
 *UnityVersion:   2019.4.16f1
 *Date:           2021-07-28
 *Description:    IFramework
 *History:        2018.11--
*********************************************************************************/
using System.Collections.Generic;
using UnityEngine;

namespace IFramework.Utility.AtlasBuilder
{
    public class Atlas : ScriptableObject
    {
        [System.Serializable]
        public class AtlasData
        {
            public Rect rect;
            public string name;
            public Vector2 pivot;
            public float pixelsPerUnit;
        }
#if UNITY_EDITOR
        public Texture2D[] sources;
#endif
        public int padding = 0;
        public int maximumAtlasSize = 1024;
        public bool compress = true;
        public Texture2D texture;
        [SerializeField]public AtlasData[] data;


        [System.NonSerialized] private Dictionary<int, Sprite> sprites = new Dictionary<int, Sprite>();
        [System.NonSerialized] private Dictionary<string, int> names = new Dictionary<string, int>();

        public Sprite GetSprite(string name)
        {
            int index = -1;
            if (!names.TryGetValue(name, out index))
            {
                for (int i = 0; i < data.Length; i++)
                {
                    if (data[i].name == name)
                    {
                        index = i;
                        names.Add(name, index);
                        break;
                    }
                }
            }
            if (index < 0) return null;
            return GetSprite(index);
        }
        public Sprite GetSprite(int index)
        {
            if (texture == null || index > data.Length || index < 0) return null;
            Sprite sp;
            sprites.TryGetValue(index, out sp);
            if (sp == null)
            {
                sp = Create(index);
            }

            return sp;
        }

        private Sprite Create(int index)
        {
            AtlasData _data = data[index];
            Sprite sp = Sprite.Create(texture, _data.rect, _data.pivot, _data.pixelsPerUnit);
            sp.name = _data.name;
            if (!sprites.ContainsKey(index))
            {
                sprites.Add(index, sp);
            }
            else
            {
                sprites[index] = sp;
            }
            return sp;
        }
    }
}
